// pages/form/index.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		...makeData(),
		saleId: 0,
		storeId: 0,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		const globalOptions = wx.getLaunchOptionsSync();
		console.log('form onload', options, globalOptions)

		if (globalOptions.store_id) {
			this.data.storeId = globalOptions.store_id;
		}
		if (options.store_id) {
			this.data.storeId = options.store_id;
		}

		if (globalOptions.sale_id) {
			this.data.saleId = globalOptions.sale_id;
		}
		if (options.sale_id) {
			this.data.saleId = options.sale_id;
		}

		wx.$emitter.on('choose.doctor', this.chooseDoctor);
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		wx.$emitter.off('choose.doctor', this.chooseDoctor);
	},

	/**
	 * 选择医师
	 */
	chooseDoctor: function(res) {
		this.setData({
			doctor: res
		})
	},

	/**
	 * 选择地址
	 */
	chooseLocation: function() {
		wx.$chooseLocation({}).then((res) => {
			this.setData({
				location: res
			})
		}, function(err) {
			console.log(err)
		});
	},

	/**
	 * 商家入驻
	 */
	joinSubmit: function(e) {
		const values = e.detail.value;
		values.name = values.name.trim();
		values.phone = values.phone.trim();

		if (!values.name.length) {
			return wx.hintError("请填写姓名");
		}

		if (!values.phone.length) {
			return wx.hintError("请填写手机号");
		}

		if (!/^[1][0-9]{10}$/.test(values.phone)) {
			return wx.hintError("请填写正确的手机号");
		}

		const location = this.data.location;
		if (!location) {
			return wx.hintError("请选择地址");
		}
		values.latitude = location.latitude;
		values.longitude = location.longitude;
		values.address = location.address;

		// const doctor = this.data.doctor;
		// if (!doctor) {
		// 	return wx.hintError("请选择医师");
		// }
		// values.doctor_id = doctor.id;

		values.sale_id = this.data.saleId;
		values.store_id = this.data.storeId;
		wx.$trySyncUserInfo().then(function() {
			return wx.$model.store.join(values, {
				loading: true,
				logicCodeHandles: {
					40401: function() {
						setTimeout(function() {
							wx.reLaunch({
								url: '/pages/index/index'
							});
						}, 1500);
					}
				}
			});
		}).then(() => {
			wx.showModal({
				content: '已提交申请！',
				showCancel: false,
				success(res) {
					wx.reLaunch({
						url: '/pages/index/index'
					});
				}
			});
		});
	}
});

function makeData() {
	return {
		name: '',
		phone: '',
		location: null,
		// location: {
		// 	address: '河南省郑州市金水区东风路',
		// 	latitude: 34.79977,
		// 	longitude: 113.66072,
		// },
	};
}
